/* eslint-disable react/require-default-props */
/**
 * 配置职位角色中的自定义表单控件
 * select
 */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Spin, Cascader } from 'antd';
import { getEffectSource, everyRequire } from './utils';

const CascaderForm = React.forwardRef(({ onChange, value, getData, params, ...rest }, ref) => {
    const { selectProps, fieldsName, requireParam } = rest;
    const { selectValue, selectTitle, selectChildren } = fieldsName;
    const [selectList, setSelectList] = useState([]);
    const [loading, setLoading] = useState(false);
    const fetchList = async () => {
        if (!everyRequire(params, requireParam)) return;
        setLoading(true);
        const result = await getData(params);
        setLoading(false);
        setSelectList(result || []);
    };
    useEffect(() => {
        fetchList();
    }, getEffectSource(params));
    return (
        <Spin spinning={loading}>
            <Cascader
                ref={ref}
                value={value || undefined}
                options={selectList}
                fieldNames={{ label: selectTitle, value: selectValue, children: selectChildren }}
                onChange={onChange}
                {...selectProps}
            />
        </Spin>
    );
});

CascaderForm.propTypes = {
    onChange: PropTypes.func,
    /**
     * request 请求参数
     */
    params: PropTypes.object,
    /**
     * 获取数据
     */
    getData: PropTypes.func,
    /**
     * 自定义字段
     */
    fieldsName: PropTypes.object,
    // select 属性
    selectProps: PropTypes.object
};

CascaderForm.defaultProps = {
    onChange: () => {},
    selectProps: {}
};

export default CascaderForm;
